'''
Created on Oct 20, 2009

@author: mkiyer
'''
import os
import glob
import sys
import logging
from parse_cufflinks_results import parse_transcripts_tmap, parse_transcripts_expr

def write_bed_line(fhd, chrom, start, end, name, score):
    s = '\t'.join([chrom,
                   str(start),
                   str(end),
                   name,
                   '%.4f' % float(score)])
    fhd.write('%s\n' % s)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    results_path = sys.argv[1]
    tmap_files = glob.glob(os.path.join(results_path, "*.tmap"))    
    unknown_fhd = open('unknown_transcripts.txt', 'w')
    libraries = []
    
    # check to make sure all the tmap files have matching expr files
    for tmap_file in tmap_files:
        library_id = os.path.splitext(os.path.basename(tmap_file))[0]
        expr_file = os.path.join(results_path, library_id + '.expr')
        if not os.path.exists(expr_file):
            print 'Error: expr file not found', expr_file
            sys.exit(0)

#    stop_after = 2
    for i, tmap_file in enumerate(tmap_files):
#        if i == stop_after:
#            break        
        logging.debug("parsing transcript map file %s" % (tmap_file)) 
        library_id = os.path.splitext(os.path.basename(tmap_file))[0]
        libraries.append(library_id)
        
        expr_file = os.path.join(results_path, library_id + '.expr')
        logging.debug("parsing transcript expression file %s" % (expr_file)) 
        transcripts_expr = {}
        for t in parse_transcripts_expr(open(expr_file)):
            transcripts_expr[t.id] = t

        print '    reading tmap file'
        num_transcripts = 0
        num_unknown = 0
        for tx in parse_transcripts_tmap(open(tmap_file)):
            num_transcripts += 1
            if tx.class_code == 'u':
                num_unknown += 1
                texpr = transcripts_expr[tx.cuff_id]
                write_bed_line(unknown_fhd, texpr.chrom, texpr.start, texpr.end, 
                               texpr.id, texpr.rpkm)
        print library_id, num_transcripts, num_unknown    
    
    unknown_fhd.close()        




